<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Session;

header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept,USER_ID,TOKEN");
header("Access-Control-Allow-Methods:HEAD, GET, POST, DELETE, PUT, OPTIONS");

/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class Alipay extends Controller {
    /**
     * 支付宝订单信息接口
     * */
    public function data(){
        vendor('alipay.AopSdk');
        vendor('alipay.aop.request.AlipayTradeAppPayRequest');
        $money = $_GET['money'];
        $user_id = $_GET['user_id'];
        $build_order_no = $this->build_order_no();
        $aop = new \AopClient;
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = "2017112800223041";
        $aop->rsaPrivateKey = 'MIIEpAIBAAKCAQEAqmzVyysxvM96H4kUsI1YRlIO0MpZAHgVjwp1fJFk79AKaCqsIwAaQev2B14tc2DVVs+TYM1YiHOcXPgg72HYAVUWioOX9IKKyipwCKmrfH+SC/25VYz7qFShkB3+MHk7Cv56ShaguPEyCPiGnh8gSbyQp32KcGgyTEUvUk7jfr4574cdLtk0Vd43mTqqOc3Y2uv20+WViKK9KvDsheieSLziccYVk0FxEb8ojAlRQbxc8EacR79BZKa94eoVW0eK4ubkS47S04W81QAvdbK5jmf6ZuBoSHO0/kvmAFb96k/5kLWfosgheFWaIuUoiR1f4k54n6uMurwx8zqfTh35JwIDAQABAoIBAQCpVTxUA1YHEWt5O/4Xskk8jbn00KkAI1DgcHbtz5UoBmDgwU2J9Uchqu8owPWOB2/SMqtv6niGE8EQSuaGk4RJRp7//+KS6sY2O1ZX9SXTrPmS+oYUr+E4juZ8yKBQz5PPx6wAQ11shRK/ARjYsXqmaTqdgMp2B8G6MJ/lO0clHQRJv51m0kPrBD/0kKkHF+LcwYkVJnXH5p9qSSAoM/5EeA1SzMB0QZh73dGScHQuvgJt23Aa+oILiLcZvftNX1VGuD9v7/Egh9ma4UTrv0Zk5+FPZoT4ZxwYTs0mPweNviy2tHR30TkypFi83L3y1m57EmD4m2Co0KvFFs9Qpy4xAoGBANWwliYvIn7T8W09mwVOi0C3Vu58LwhraRHnP9GZUU8D+DR5dliqFj0g+z/OzheuWaNdn4Kf8EGfVgHt8VWMjxsDAhmdoQwwV68eCCLCUyxSynpxCxT9yhHTUvx08mYayhNizYtygv350Z1TKc45g8TjVrzH/DcwGBy9QNYoSadvAoGBAMwrRN0q/+OK/XWrMkROYOjM9dv7a/QWZxlN40CO277O3WKdH2mPvckddcJkNX6THxm4JptiuVBBAGnbJQg9685NZHyF0sFZDL8QgrrhcME/kbJtJsk/zcjVM6IykgljpZue/wGKehclcKbIuGWpmYeNpGRkkZKQUw4BbDD+VS3JAoGATsXU4+iWP8ijhBCkt9UXcljjm/B9ag4mYmor1Xk+RvGAqt9nqBGzNv+UfxYeVQ55jsZxibap25cAHp/3SgERs/Rs7sJz3slnWW+psh6OiJVQfMh1PFy+A8oyGkyGGuufOHxApzokXbmc8vD4RURgddEUZW0XZcS97sI5R3j8hdMCgYAOHywLNC8w2OtBGU9HxDgVwh97UL+dyXLmICoIzBjM8NgFOyLyFTwmTgBYKsA8egabq84Xz1NMBsL1j2/XSxklUtsRddwm/XbRPF4eePtoknIMalpVbzFXo8+Hd4H8XkUVJ4Ex5RcexLsu/hErDvkMlDJ7sy0SeyMTg+us09qmaQKBgQDUcYYev1ySYKylYlXZ7vgwqAwbnnsbIUzWFWUAyYQUn3cV+mbJ6GUj8u7cNs1bOv25Y3wXpNJOdSxrkL/vkZt5oi3tGDsX09KbzB5F3L+IdaG4qF+rg/JrvGn4sw6mZqf59g4Djg9paTPbwm0fcfOnZy9i+uNidK7FVkWg1CKPfA==';
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAidGwyseWLTTKfF/BjzMSYCOSMNn2TgHeglAV2iMsc1vRYeCqRsBnhXdg+UrSvUWI28lpsV+eE/CG//2ArbbMHuL2snXcIr4GzNWrjQw/TNnkQM+tkcMw7PTkLaALOSUwart+rNAsy/ZLJDHtJHNqlYIBc03eCv3z9J+pSodluV3NL/ByjBBNZDr5msP0LyrrPud0CbQ35CAB0mu3AfASVCf23IXQnjhX9c1CC+f4HCYUhJkU6lb854P473Tq5qcRIkmMrE/jKlr977iIht8DECb9UchUN9DT6fRNlZ1kZzYuqaVaRIAH1QIL1MeuARZQzsa9qcUXko3ShE7006ktdQIDAQAB';
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $request = new \AlipayTradeAppPayRequest;
        //SDK已经封装掉了公共参数，这里只需要传入业务参数
        $bizcontent = "{\"body\":\"$user_id\","
            . "\"subject\": \"拾友充值\","
            . "\"out_trade_no\": \"$build_order_no\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"$money\","
            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
            . "}";
        $request->setNotifyUrl("http://tour.mgtvshop.com/index/alipay/call_back");
        $request->setBizContent($bizcontent);
        //这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);
        $data = array(
            'order_trade' => $build_order_no,
            'ordfee' => $money,
            'userid' => $user_id,
            'ordtime' => time(),
            'ordstatus' => 0,
            'payment_type' => 2,
        );
        $res = Db::table('tp_order')->insert($data);
        if($res){
            //htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
            echo $response;
            //echo htmlspecialchars($response);//就是orderString 可以直接给客户端请求，无需再做处理。
        }else{
            echo "订单创建失败";
        }
    }

    /**
     * 支付宝回调
     * */
    function call_back()
    {
        Vendor('alipay.AopSdk');
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAidGwyseWLTTKfF/BjzMSYCOSMNn2TgHeglAV2iMsc1vRYeCqRsBnhXdg+UrSvUWI28lpsV+eE/CG//2ArbbMHuL2snXcIr4GzNWrjQw/TNnkQM+tkcMw7PTkLaALOSUwart+rNAsy/ZLJDHtJHNqlYIBc03eCv3z9J+pSodluV3NL/ByjBBNZDr5msP0LyrrPud0CbQ35CAB0mu3AfASVCf23IXQnjhX9c1CC+f4HCYUhJkU6lb854P473Tq5qcRIkmMrE/jKlr977iIht8DECb9UchUN9DT6fRNlZ1kZzYuqaVaRIAH1QIL1MeuARZQzsa9qcUXko3ShE7006ktdQIDAQAB';
        //此处验签方式必须与下单时的签名方式一致
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");

        $user_id = $_POST['body'];
        $order_info = Db::table('tp_order')->where(['userid'=>$user_id])->order('id desc')->find();

        file_put_contents(RUNTIME_PATH.'sql.txt',Db::table('tp_order')->getLastSql());

        $out_trade_no = $order_info['order_trade'];//订单号
        $total_amount = $order_info['ordfee'];//订单金额
        $seller_id = "2088221367181845";
        $app_id = "2017112800223041";

        file_put_contents(RUNTIME_PATH.'db_data.txt',$out_trade_no.','.$total_amount);

        file_put_contents(RUNTIME_PATH.'call_back.txt',json_encode($_POST));
        if($_POST['out_trade_no'] == $out_trade_no && $_POST['total_amount'] == $total_amount && $_POST['seller_id'] == $seller_id && $_POST['app_id'] == $app_id){
            Db::startTrans();

            try{
                Db::table('tp_order')->where(['order_trade'=>$out_trade_no])->update(['ordstatus'=>1]);//订单状态修改成已完成

                Db::table('tp_user')->where(['id' => $user_id])->setInc('money',$total_amount);//增加用户余额

                //打印success，应答支付宝。必须保证本界面无错误。只打印了success，否则支付宝将重复请求回调地址。
                //验签通过后再实现业务逻辑，比如修改订单表中的支付状态。
                /**
                ①验签通过后核实如下参数trade_status、out_trade_no、total_amount、seller_id
                ②修改订单表
                 **/

                echo 'success';

                Db::commit();
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                echo '支付失败';
            }

        }else{
            echo "支付异常";
        }
    }

    /**
     * 获得随机订单号
     * */
    function build_order_no(){
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
}